package com.violet.uaa.server.security.handler;

import cn.hutool.json.JSONUtil;
import com.violet.common.constant.business.CodeEnum;
import com.violet.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 类说明: spring security 当认证失败时，此方法会被调用
 *
 * @author wqf
 * @date 2022/6/14 14:13
 */
@Slf4j
@Component
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        // 设置响应头，允许任何域进行跨域请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 设置响应头，指示响应不应被缓存
        response.setHeader("Cache-Control", "no-cache");
        // 设置响应的字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        // 将认证失败的消息写入响应体
        try (ServletOutputStream ous = response.getOutputStream()) {
            Result<Object> result = Result.failure(CodeEnum.USER_IDENTITY_NOT_AUTHENTICATED.getCode(), "用户身份认证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            ous.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        }
    }
}
